package com.drd.dt.modular.service.impl;

import com.drd.dt.back.dao.BackCommonMapper;
import com.drd.dt.back.dto.JGPushDTO;
import com.drd.dt.common.Constant;
import com.drd.dt.filter.UserThreadLocal;
import com.drd.dt.modular.dao.UserMapper;
import com.drd.dt.modular.dao.UserMoneyMapper;
import com.drd.dt.modular.entity.*;
import com.drd.dt.util.EmojiUtil;
import com.drd.dt.util.JgPushUtil;
import io.swagger.models.auth.In;
import org.apache.http.util.TextUtils;
import org.omg.CORBA.INTERNAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

@Transactional
@Service
public class UserMoneyServiceImpl {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMoneyMapper userMoneyMapper;
    @Autowired
    private BackCommonMapper commonMapper;

    /**
     * 预获取下一级的预估返佣比例，适合预判下一级的返佣比例
     *
     * @param selfRakeRate
     * @return
     */
    public double getUpLevelRakeBackRate(double selfRakeRate) {

        if (selfRakeRate == 0.55) {
            return 0.82;
        } else if (selfRakeRate == 0.82) {
            return 0.87;
        } else if (selfRakeRate == 0.87) {
            return 0.9;
        } else {
            return 0.9;
        }

    }

    /**
     * 预获自己的预估返佣比例，适合商品返利计算
     *
     * @param userid
     * @return
     */
    public double getSelftRakeBackRate(Integer userid) {
        if (StringUtils.isEmpty(userid) || userid <= 0) {
            return 0.55;
        }
        Map map = new HashMap();
        Integer id = userid;
        map.put("id", id);
//        User user = userMoneyMapper.getByUserId(map);
        User user = UserThreadLocal.get();
        Integer level = user.getLevel();

        if (level == 0) {
            return 0.55;
        } else if (level == 1) {
            return 0.82;
        } else if (level == 2) {
            return 0.87;
        } else {
            return 0.9;
        }

    }

    /**
     * 自购用户获取返佣比例
     *
     * @param user
     * @return
     */
    public double getRakeBackRatebyUser(User user) {
        if (user == null) {
            return 0.55;
        }
        if (user.getLevel() == 0) {
            return 0.55;
        }
        List<User> userList = queryUpUserListByBaseUser(user);
        if (checkUpVipLeveByList(userList, user)) {//如果自购是会员级别，并且上一级也是会员同级，则将固定比例减少5%
            if (user.getLevel() == 1) {
                return 0.82 - 0.05;
            } else if (user.getLevel() == 2) {
                return 0.87 - 0.02;
            } else if (user.getLevel() == 3) {
                return 0.9 - 0.01;
            }

        }
        if (user.getLevel() == 1) {
            return 0.82;
        } else if (user.getLevel() == 2) {
            return 0.87;
        } else if (user.getLevel() == 3) {
            return 0.9;
        }
        return 0;
    }

    /**
     * 通过新注册用户，计算他上级和上上级的直粉和间粉数
     */
    public void updateUserFansNum(User newUser) {

        Map map1 = new HashMap();
        map1.put("id", newUser.getId());
        newUser = userMoneyMapper.getByUserId(map1);//外部参数不全，重新查询 用户全部信息

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date()).toString();
        insertSysMessage(newUser.getId(), newUser.getId(), 0);
        pushJiGuangMessage(newUser.getId(), getMessageText(null, time, "", 0));//用户注册

        List<User> userList = queryUpUserListByBaseUser(newUser);
      /*  Integer introducer=newUser.getIntroducer();
        Map map = new HashMap();
        map.put("id", introducer);
        User upuser = userMoneyMapper.getByUserId(map);
        if (upuser != null) {

          Map map2 = new HashMap();
            map2.put("id", upuser.getIntroducer());
            upuser = userMoneyMapper.getByUserId(map2);
            if (upuser != null) {
                UserMoney money2 = new UserMoney();
                money2.setUser_id(upuser.getId());
                money2.setIndirect_fans(1);
                userMoneyMapper.updateUserMoney(money2);//间粉数量+1
            }
        }*/
        for (int i = 1; i < userList.size(); i++) {//从1开始
            User user = userList.get(i);
            if (i == 1) {
                if (user.getLevel() >= newUser.getLevel()) {//直 允许同级推送
                    insertSysMessage(user.getId(), newUser.getId(), 0);
                    pushJiGuangMessage(user.getId(), getMessageText(newUser.getNick_name(), time, "", 0));//用户注册
                }
                UserMoney money = new UserMoney();
                money.setUser_id(user.getId());
                money.setDirect_fans(1);
                userMoneyMapper.updateUserMoney(money);//直粉数量+1
            } else {
                if (user.getLevel() > newUser.getLevel()) {
                    pushJiGuangMessage(user.getId(), getMessageText(newUser.getNick_name(), time, "", 0));//用户注册
                }
                insertSysMessage(user.getId(), newUser.getId(), 0);
                UserMoney money2 = new UserMoney();
                money2.setUser_id(user.getId());
                money2.setIndirect_fans(1);
                userMoneyMapper.updateUserMoney(money2);//普粉数量+1
            }
            if (user.getLevel() == 0) {//如果是普通粉丝，他的直粉达到100，总粉200，则升级为超级会员
                Map map2 = new HashMap();
                map2.put("user_id", user.getId());
                UserMoney profit = userMoneyMapper.getByUserMoneyId(map2);
                if (profit != null) {
                    if (profit.getDirect_fans() >= 100 && (profit.getDirect_fans() + profit.getIndirect_fans() >= 200)) {
                        Date nowt = new Date();
                        user.setLv_start_time(sdf.format(nowt).toString());
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(nowt);//设置起时间
                        cal.add(Calendar.YEAR, 1);//增加一年
                        user.setLv_expire_time(sdf.format(cal.getTime()).toString());
                        userMoneyMapper.updateUserLevelAndTime(user);//先更新购买礼包用户的会员等级和时间
                        insertSysMessage(user.getId(), user.getId(), 4);
                        pushJiGuangMessage(user.getId(), getMessageText(null, user.getLv_expire_time(), "", 4));//用户升级
                    }
                }
            }


        }
    }

    private void insertSysMessage(int user_d, int origin_id, int type) {
        Map map = new HashMap();
        String title = "欢迎注册";
        map.put("user_id", user_d);
        map.put("origin_id", origin_id);
        if (type == 0) {//注册
            if (user_d != origin_id) {
                title = "邀请成功！";
                map.put("type", 2);
            } else {
                title = "欢迎注册";
                map.put("type", 1);

                if (userMoneyMapper.checkRegisterMsg(map) > 0) {
                    return;
                }
            }
        } else if (type == 4) {//升级
            title = "会员升级成功！";
            map.put("type", 3);
        }
        map.put("title", title);

        userMoneyMapper.insertSYSMessage(map);
    }

    /**
     * 通过购买礼包的Userid去更新
     *
     * @param userid
     * @param gift
     */
    public void updateOrderGiftRake(int userid, OrderGift gift) {
        Map map = new HashMap();
        map.put("id", userid);
        User user = userMoneyMapper.getByUserId(map);
        updateOrderGiftRake(user, gift);
    }

    /**
     * 根据购买礼包用户，订单信息计算推荐佣金
     *
     * @param user
     * @param gift
     */
    public void updateOrderGiftRake(User user, OrderGift gift) {
        if (user.getLevel() == 0) {//如果是普通 用户购买
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date nowt = new Date();
            user.setLv_start_time(sdf.format(nowt).toString());
            Calendar cal = Calendar.getInstance();
            cal.setTime(nowt);//设置起时间
            cal.add(Calendar.YEAR, 1);//增加一年
            user.setLv_expire_time(sdf.format(cal.getTime()).toString());
            userMoneyMapper.updateUserLevelAndTime(user);//先更新购买礼包用户的会员等级和时间
            insertSysMessage(user.getId(), user.getId(), 4);
            pushJiGuangMessage(user.getId(), getMessageText(null, user.getLv_expire_time(), "", 4));//用户升级
        }

        List<User> userList = queryUpUserListByBaseUser(user);
        int userid = user.getId();
        User upuser = getUpUserByUser(userList, user);
        if (upuser != null) {//有上级,直属人头奖励
            if (upuser.getLevel() == 0) {//上级是普通用户，则直接遍历直接找到最近的>=1的上级
                while (true) {//继续找最近的VIP
                    upuser = getUpUserByUser(userList, upuser);
                    if (upuser != null) {//找到上一级,计算团队收益
                        if (upuser.getLevel() > 0) {
                            break;
                        }
                    } else {
                        return;
                    }
                }
            }
            OrderGiftRake rake = new OrderGiftRake();
            rake.setUser_id(upuser.getId());
            rake.setOrder_id(gift.getOrder_id());
            rake.setOrigin_id(user.getId());
            if (upuser.getLevel() == 1) {
                rake.setUser_rake_back(100 + "");
                rake.setRake_type("直属奖励100");
            } else if (upuser.getLevel() == 2) {
                rake.setUser_rake_back(150 + "");
                rake.setRake_type("直属奖励150");
            } else if (upuser.getLevel() == 3) {
                rake.setUser_rake_back(200 + "");
                rake.setRake_type("直属奖励200");

            } else {
                return;//没有找到可以返佣的上级，结束
            }
            userMoneyMapper.insertGiftRake(rake);
            //判断等级是否要晋升
            if (checkUpgrade(upuser)) {
                userMoneyMapper.updateUserLevel(upuser);

                insertSysMessage(upuser.getId(), upuser.getId(), 4);
                pushJiGuangMessage(upuser.getId(), getMessageText(user.getNick_name(), upuser.getLv_expire_time(), "", 4));//用户升级
            }
            insertMessage(upuser.getId(), user, gift.getOrder_id(), 0, Double.parseDouble(rake.getUser_rake_back()), Double.parseDouble(gift.getActual_amount()), 3);
            updateBounty_accumulated(upuser, Double.parseDouble(rake.getUser_rake_back()));
            if (checkUpVipLeveByList2(userList, upuser)) {//如果向上还有更高级，则去计算上级佣金
                repeatGroupGift(userList, upuser, gift, user, upuser.getLevel(), true);
            }


        }
    }

    /**
     * 调用极光推广，精确推送给用户ID
     *
     * @param user_id
     * @param text
     */
    private void pushJiGuangMessage(int user_id, String text) {
        Map jg = commonMapper.getJgInfoAndUser(user_id);
        if (null != jg) {
            String user_jp_id = jg.get("jp_id").toString();
            String deviceT = jg.get("deviceT").toString();//客户端类型（Android:0  IOS:1）
            String masterSecret = jg.get("jg_app_secret").toString();
            String appKey = jg.get("jg_app_key").toString();
            //ios使用券巴士的极光
            String ios_appKey = Constant.QBS_JG_APPKEY;
            String ios_masterSecret = Constant.QBS_JG_APPSECRET;
            if (!StringUtils.isEmpty(user_jp_id) && !StringUtils.isEmpty(deviceT)) {
                Integer dev = Integer.valueOf(deviceT);//客户端类型（Android:0  IOS:1）
                try {
                    JGPushDTO dto = new JGPushDTO();
                    dto.setJump_action(2);
                    dto.setIs_login(0);
                    if (dev == 0) {
                        JgPushUtil.pushMsg(text, dto, appKey, masterSecret, user_jp_id);
                    } else if (dev == 1) {
                        JgPushUtil.pushMsg(text, dto, ios_appKey, ios_masterSecret, user_jp_id);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取消息模板
     *
     * @param fansName
     * @param time
     * @param money
     * @param type     0，用户注册邀请成功 1 普通收益，2，奖励收益 3，普通退款扣除 4，升级VIP 10,信用卡订单预估返佣
     * @return
     */
    public String getMessageText(String fansName, String time, String money, int type) {
        String text = "";
        if (fansName != null) {
            fansName = EmojiUtil.decode(fansName);
        }
        if (type == 0) {
            if (TextUtils.isEmpty(fansName)) {//自己注册
                text = "欢迎注册[核桃省钱]会员，免费使用核桃购买和分享都可以获得高额返佣，VIP可获得更多专属尊贵权益。快开启省赚模式吧。";
            } else {//粉丝注册
                text = "恭喜您成功邀请到【" + fansName + "】" + "加入核桃省钱大家庭，快带小伙伴开启创业之旅吧。";
            }
        } else if (type == 1) {
            if (TextUtils.isEmpty(fansName)) {//自购
                text = "您在" + time + "推广成功，预估普通佣金:" + money + "元，预估结算时间：收货后次月25日结算";
            } else {//粉丝购
                text = "您的粉丝【" + fansName + "】在" + time + "推广成功，预估普通佣金:" + money + "元，预估结算时间：收货后次月25日结算";
            }
        } else if (type == 2) {//粉丝购VIP
            text = "您的粉丝【" + fansName + "】在" + time + "成功推广，奖励佣金:" + money + "元";
        } else if (type == 3) {
            if (TextUtils.isEmpty(fansName)) {//自购订单退款
                text = "您在" + time + "推广的订单因【退款】失效";
            } else {//粉丝订单退款
                text = "您的粉丝【" + fansName + "】在" + time + "推广的订单因【退款】失效";
            }

        } else if (type == 4) {//自己升级VIP
            text = "恭喜您成功升级VIP，" + time + "前均可享受VIP权益。";
        } else if (type == 10) {//信用卡订单审核通过
            text = "您于" + time + " 卡多分推广成功 并达到返佣标准,预估返佣:" + money + "元,预估结算时间：次月1号";
        } else if (type == 11) {//信用卡推广失败
            if (TextUtils.isEmpty(fansName)) {//自购订单退款
                text = "您于" + time + "卡多分推广失败";
            } else {//粉丝订单退款
                text = "您的粉丝【" + fansName + "】于" + time + "卡多分推广失败 ";
            }
        }
        return text;
    }

    /**
     * 计算当前被返的用户是否达到升级标准，如果达到升级标准，把等级+1
     *
     * @return
     */
    private boolean checkUpgrade(User user) {
        if (user.getLevel() < 3 && user.getLevel() > 0) {//VIP和运营商才有
            long num = userMoneyMapper.countUserVipNumByLevel(user);
            if (user.getLevel() == 1) {
                if (num == 20) {
                    return true;
                }
            } else if (user.getLevel() == 2) {
                if (num == 10) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 将该用户所有的上级用户串，一条线全部查完
     *
     * @param user
     * @return
     */
    private List<User> queryUpUserListByBaseUser(User user) {
        List<User> userList = new ArrayList<User>();
        userList.add(user);//将基础也加进来
        Map map = new HashMap();
        Integer id = user.getIntroducer();
        while (true) {
            map.put("id", id);
            User upuser = userMoneyMapper.getByUserId(map);
            if (upuser != null) {
                userList.add(upuser);
                id = upuser.getIntroducer();
            } else {
                break;
            }
        }

        return userList;
    }

    /**
     * 根据当前用户去LIST查找他的直接上级
     *
     * @param userList
     * @param user
     * @return
     */
    private User getUpUserByUser(List<User> userList, User user) {
        int startIndex = userList.indexOf(user) + 1;
        if (startIndex < userList.size()) {
            return userList.get(startIndex);
        }
        return null;
    }

    /**
     * 根据变动的订单进行 返佣计算
     *
     * @param order
     */
    public void updateOrderFansRake(Order order) {
        Map mapuser = new HashMap();
        int userid = order.getUser_id();
        if (userid > 0) {
            mapuser.put("id", userid);
            User user = userMoneyMapper.getByUserId(mapuser);
            updateOrderFansRake(user, order);
        }

    }

    /**
     * 根据下单用户及订单信息，计算粉丝订单
     *
     * @param user
     * @param order
     */
    public void updateOrderFansRake(User user, Order order) {
        double selfmoney = Double.parseDouble(round(order.getUser_rake_back_yugu()));
        //  userMoneyMapper.insertOrder(order);//此两步逻辑交给外部实现
//        if (order.getStatus() == 2 || order.getStatus() == 4) {//新增或失效，更新消息
//            insertNormalMessage(user, user, order, null);//自购消息
//        }
        /*******新增信用卡逻辑****/
        /***
         *  当type = 10   ,1订单结算 2 审核通过，3 审核中 ， 4 审核不 通过 5带查询  6未完成7 异常订单 8 失效订单
         * */
        if (order.getType() == 10 &&
                (order.getStatus() == 2 ||
                        order.getStatus() == 7 ||
                        order.getStatus() == 8)) {//信用卡订单
            insertNormalMessage(user, user, order, null);//自购消息
        } else if (order.getStatus() == 2 || order.getStatus() == 4) {//新增或失效，更新消息
            insertNormalMessage(user, user, order, null);//自购消息
        }

        updateOwner_estimate(user, order, selfmoney, order.getRedpacket());//首先更新下单用户的普通预估
        Boolean is_zeroParchase = order.getIs_zeroParchase();
        if (is_zeroParchase) {//有零元购商品时，不进行上级返佣
            return;
        }

        List<User> userList = queryUpUserListByBaseUser(user);
//        if (order.getStatus() == 2) {//新增预估订单
//            int userid = user.getId();
//            if (user.getLevel() == 0) {//普通用户下单
//                User upuser = getUpUserByUser(userList, user);
//                if (upuser != null) {//有上级
//                    if (upuser.getLevel() == 0) {//直接上级为普通级别，返5%
//                        Double rate = 0.05;
//                        OrderFansRake fansRake = new OrderFansRake();
//                        fansRake.setOrder_id(order.getOrder_id());
//                        fansRake.setUser_id(upuser.getId());//用户ID
//                        fansRake.setOrigin_id(userid);//来源用户ID
//                        fansRake.setRake_rate(rate + "");
//                        fansRake.setRake_back(order.getRake_back());//总佣金
//                        fansRake.setUser_rake_back(round(rate * Double.parseDouble(order.getRake_back()) + ""));//该上级返佣
//                        fansRake.setRake_type("直属普通5");
//                        fansRake.setStatus(order.getStatus());
//                        if (Double.parseDouble(round(rate * Double.parseDouble(order.getRake_back()) + "")) <= 0) {//如果佣金为0,就不通知，不做处理
//                            return;
//                        }
//                        userMoneyMapper.insertFansRake(fansRake);
//                        insertNormalMessage(upuser, user, order, fansRake);
//                        updateFans_estimate(upuser, order, Double.parseDouble(fansRake.getUser_rake_back()));
//                        while (true) {//继续找最近的VIP
//                            upuser = getUpUserByUser(userList, upuser);
//                            if (upuser != null) {//找到上一级,计算团队收益
//                                if (upuser.getLevel() > 0) {//找到VIP
//                                    if (upuser.getLevel() == 1) {//超级会员 22
//                                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
//                                            insertFanceRake(userList, upuser, order, user, 0.17, "间接返佣17");
//                                        } else {
//                                            insertFanceRake(userList, upuser, order, user, 0.22, "间接返佣22");
//                                        }
//
//                                    } else if (upuser.getLevel() == 2) {//运营商 28
//                                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
//                                            insertFanceRake(userList, upuser, order, user, 0.25, "间接返佣25");
//                                        } else {
//                                            insertFanceRake(userList, upuser, order, user, 0.27, "间接返佣27");
//                                        }
//
//
//                                    } else if (upuser.getLevel() == 3) {//联创 32
//                                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
//                                            insertFanceRake(userList, upuser, order, user, 0.29, "间接返佣29");
//                                        } else {
//                                            insertFanceRake(userList, upuser, order, user, 0.30, "间接返佣30");
//                                        }
//
//                                    }
//                                    break;//找到间接返佣金目标，结束查找
//                                }
//
//                            } else {
//                                break;
//                            }
//                        }
//                    } else if (upuser.getLevel() == 1) {//超级会员 27
//                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
//                            insertFanceRake(userList, upuser, order, user, 0.22, "直属返佣22");
//                        } else {
//                            insertFanceRake(userList, upuser, order, user, 0.27, "直属返佣27");
//                        }
//
//
//                    } else if (upuser.getLevel() == 2) {//运营商 33
//                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
//                            insertFanceRake(userList, upuser, order, user, 0.30, "直属返佣30");
//                        } else {
//                            insertFanceRake(userList, upuser, order, user, 0.32, "直属返佣32");
//                        }
//
//
//                    } else if (upuser.getLevel() == 3) {//联创 37
//                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
//                            insertFanceRake(userList, upuser, order, user, 0.34, "直属返佣34");
//                        } else {
//                            insertFanceRake(userList, upuser, order, user, 0.35, "直属返佣35");
//                        }
//
//
//                    }
//                }
//
//            } else {//VIP下单
//                if (checkUpVipLeveByList2(userList, user)) {
//                    repeatGroupCPS(userList, user, order, user, user.getLevel(), true);
//                }
//
//            }
//        } else {//结算或者失效
//            //   updateFans_estimate()
//            Map map = new HashMap();
//            map.put("order_id", order.getOrder_id());
//            List<OrderFansRake> fansList = userMoneyMapper.queryFansRakeByOrderId(map);
//            if (fansList != null) {
//                for (OrderFansRake fans : fansList) {
//                    User tempUser = new User();
//                    tempUser.setId(fans.getUser_id());
//                    double money = Double.parseDouble(fans.getUser_rake_back());
//                    updateFans_estimate(tempUser, order, money);
//                    if (order.getStatus() == 1) {
//                        Map balance = new HashMap();
//                        balance.put("user_id", fans.getUser_id());
//                        balance.put("origin_id", fans.getOrigin_id());
//                        balance.put("money", money);
//                        balance.put("action_type", Constant.BALANCE_ACTION_ADD);
//                        balance.put("type", Constant.BALANCE_TYPE_FANCE);
//                        balance.put("remark", "粉丝返佣");
//                        balance.put("order_id", order.getOrder_id());
//                        userMoneyMapper.insertBalanceDetailNew(balance);
//                    } else if (order.getStatus() == 4) {//失效的时候，通知上级已经返钱的订单，维权了
//                        insertNormalMessage(tempUser, user, order, fans);
//                    }
//                }
//            }
//
//        }
        /*******新增信用卡逻辑****/
        /***
         * 卡多分订单状态： 000 老户订单 001 带查询 002审核中 003审核通过 004 审核拒绝 005 未完成 006 异常订单
         *
         * jz_order 订单状态： 1-订单结算 2-订单付款 3-订单未付款 4-订单失效
         *            当type = 10   ,1订单结算 2 审核通过，3 审核中 ， 4 审核不 通过 5带查询  6未完成7 异常订单 8 失效订单
         * */
        if (order.getStatus() == 2) {//新增预估订单
            int userid = user.getId();
            if (user.getLevel() == 0) {//普通用户下单
                User upuser = getUpUserByUser(userList, user);
                if (upuser != null) {//有上级
                    if (upuser.getLevel() == 0) {//直接上级为普通级别，返5%
                        Double rate = 0.05;
                        OrderFansRake fansRake = new OrderFansRake();
                        fansRake.setOrder_id(order.getOrder_id());
                        fansRake.setUser_id(upuser.getId());//用户ID
                        fansRake.setOrigin_id(userid);//来源用户ID
                        fansRake.setRake_rate(rate + "");
                        fansRake.setRake_back(order.getRake_back());//总佣金
                        fansRake.setUser_rake_back(round(rate * Double.parseDouble(order.getRake_back()) + ""));//该上级返佣
                        fansRake.setRake_type("直属普通5");
                        fansRake.setStatus(order.getStatus());
                        if (Double.parseDouble(round(rate * Double.parseDouble(order.getRake_back()) + "")) <= 0) {//如果佣金为0,就不通知，不做处理
                            return;
                        }
                        userMoneyMapper.insertFansRake(fansRake);
                        insertNormalMessage(upuser, user, order, fansRake);
                        updateFans_estimate(upuser, order, Double.parseDouble(fansRake.getUser_rake_back()));
                        while (true) {//继续找最近的VIP
                            upuser = getUpUserByUser(userList, upuser);
                            if (upuser != null) {//找到上一级,计算团队收益
                                if (upuser.getLevel() > 0) {//找到VIP
                                    if (upuser.getLevel() == 1) {//超级会员 22
                                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
                                            insertFanceRake(userList, upuser, order, user, 0.17, "间接返佣17");
                                        } else {
                                            insertFanceRake(userList, upuser, order, user, 0.22, "间接返佣22");
                                        }

                                    } else if (upuser.getLevel() == 2) {//运营商 28
                                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
                                            insertFanceRake(userList, upuser, order, user, 0.25, "间接返佣25");
                                        } else {
                                            insertFanceRake(userList, upuser, order, user, 0.27, "间接返佣27");
                                        }


                                    } else if (upuser.getLevel() == 3) {//联创 32
                                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
                                            insertFanceRake(userList, upuser, order, user, 0.29, "间接返佣29");
                                        } else {
                                            insertFanceRake(userList, upuser, order, user, 0.30, "间接返佣30");
                                        }

                                    }
                                    break;//找到间接返佣金目标，结束查找
                                }

                            } else {
                                break;
                            }
                        }
                    } else if (upuser.getLevel() == 1) {//超级会员 27
                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
                            insertFanceRake(userList, upuser, order, user, 0.22, "直属返佣22");
                        } else {
                            insertFanceRake(userList, upuser, order, user, 0.27, "直属返佣27");
                        }


                    } else if (upuser.getLevel() == 2) {//运营商 33
                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
                            insertFanceRake(userList, upuser, order, user, 0.30, "直属返佣30");
                        } else {
                            insertFanceRake(userList, upuser, order, user, 0.32, "直属返佣32");
                        }


                    } else if (upuser.getLevel() == 3) {//联创 37
                        if (checkUpVipLeveByList(userList, upuser)) {//预上一级还是平级
                            insertFanceRake(userList, upuser, order, user, 0.34, "直属返佣34");
                        } else {
                            insertFanceRake(userList, upuser, order, user, 0.35, "直属返佣35");
                        }


                    }
                }

            } else {//VIP下单
                if (checkUpVipLeveByList2(userList, user)) {
                    repeatGroupCPS(userList, user, order, user, user.getLevel(), true);
                }

            }
        } else {//结算或者失效
            Map map = new HashMap();
            map.put("order_id", order.getOrder_id());
            List<OrderFansRake> fansList = userMoneyMapper.queryFansRakeByOrderId(map);
            if (fansList != null) {
                for (OrderFansRake fans : fansList) {
                    User tempUser = new User();
                    tempUser.setId(fans.getUser_id());
                    double money = Double.parseDouble(fans.getUser_rake_back());
                    updateFans_estimate(tempUser, order, money);
                    if (order.getStatus() == 1) {
                        Map balance = new HashMap();
                        balance.put("user_id", fans.getUser_id());
                        balance.put("origin_id", fans.getOrigin_id());
                        balance.put("money", money);
                        balance.put("action_type", Constant.BALANCE_ACTION_ADD);
                        balance.put("type", Constant.BALANCE_TYPE_FANCE);
                        balance.put("remark", "粉丝返佣");
                        balance.put("order_id", order.getOrder_id());
                        userMoneyMapper.insertBalanceDetailNew(balance);
                    } else if (order.getStatus() == 4) {//失效的时候，通知上级已经返钱的订单，维权了
                        insertNormalMessage(tempUser, user, order, fans);
                    }
                }
            }

        }
    }

    /**
     * 向佣金变化消息表，插入一条消息
     *
     * @param user_id
     * @param Origin_User
     * @param orderid
     * @param order_type
     * @param rake_money
     * @param money
     * @param messagetype 1 直接购收益 2 粉丝返， 3人头奖励  4，普通扣除
     */
    private void insertMessage(int user_id, User Origin_User, String orderid, int order_type, double rake_money, double money, int messagetype) {
        MessageMoney message = new MessageMoney();
        message.setMoney(money);
        message.setOrder_id(orderid);
        message.setOrder_type(order_type);
        message.setOrigin_id(Origin_User.getId());
        message.setRake_money(rake_money);
        message.setUser_id(user_id);
        message.setMessage_type(messagetype);
        userMoneyMapper.insertMessageMoney(message);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date()).toString();

        /*******新增信用卡逻辑****/
//        if (messagetype == 3) {//人头奖励，调用极光推送
//            Map balance = new HashMap();
//            balance.put("user_id", user_id);
//            balance.put("origin_id", Origin_User.getId());
//            balance.put("money", rake_money);
//            balance.put("action_type", Constant.BALANCE_ACTION_ADD);
//            balance.put("type", Constant.BALANCE_TYPE_GIFT);
//            balance.put("remark", "推荐奖励");
//            balance.put("order_id", orderid);
//            userMoneyMapper.insertBalanceDetailNew(balance);
//            pushJiGuangMessage(user_id, getMessageText(Origin_User.getNick_name(), time, rake_money + "", 2));//奖励收益
//
//        } else if (messagetype == 1) {
//            if (user_id == Origin_User.getId()) {
//                pushJiGuangMessage(user_id, getMessageText(null, time, rake_money + "", 1));//普通自购
//            }
//
//        } else if (messagetype == 2) {//粉丝返的
//            pushJiGuangMessage(user_id, getMessageText(Origin_User.getNick_name(), time, rake_money + "", 1));//普通粉丝返 ，带粉丝NAME
//        } else if (messagetype == 4) {
//            if (user_id == Origin_User.getId()) {
//                pushJiGuangMessage(user_id, getMessageText(null, time, rake_money + "", 3));//自己失效
//            } else {
//                pushJiGuangMessage(user_id, getMessageText(Origin_User.getNick_name(), time, rake_money + "", 3));//粉丝失效
//            }
//        }
        /*******新增信用卡逻辑****/
        if (order_type == 10) { //  卡多分信用卡
            if (messagetype == 1) {
                if (user_id == Origin_User.getId()) {
                    pushJiGuangMessage(user_id, getMessageText(null, time, rake_money + "", 10));//普通自购
                }

            } else if (messagetype == 2) {//粉丝返的
                pushJiGuangMessage(user_id, getMessageText(Origin_User.getNick_name(), time, rake_money + "", 10));//普通粉丝返 ，带粉丝NAME
            } else if (messagetype == 4) {
                if (user_id == Origin_User.getId()) {
                    pushJiGuangMessage(user_id, getMessageText(null, time, rake_money + "", 11));//自己失效
                } else {
                    pushJiGuangMessage(user_id, getMessageText(Origin_User.getNick_name(), time, rake_money + "", 11));//粉丝失效
                }
            }
        } else {
            if (messagetype == 3) {//人头奖励，调用极光推送
                Map balance = new HashMap();
                balance.put("user_id", user_id);
                balance.put("origin_id", Origin_User.getId());
                balance.put("money", rake_money);
                balance.put("action_type", Constant.BALANCE_ACTION_ADD);
                balance.put("type", Constant.BALANCE_TYPE_GIFT);
                balance.put("remark", "推荐奖励");
                balance.put("order_id", orderid);
                userMoneyMapper.insertBalanceDetailNew(balance);
                pushJiGuangMessage(user_id, getMessageText(Origin_User.getNick_name(), time, rake_money + "", 2));//奖励收益

            } else if (messagetype == 1) {
                if (user_id == Origin_User.getId()) {
                    pushJiGuangMessage(user_id, getMessageText(null, time, rake_money + "", 1));//普通自购
                }

            } else if (messagetype == 2) {//粉丝返的
                pushJiGuangMessage(user_id, getMessageText(Origin_User.getNick_name(), time, rake_money + "", 1));//普通粉丝返 ，带粉丝NAME
            } else if (messagetype == 4) {
                if (user_id == Origin_User.getId()) {
                    pushJiGuangMessage(user_id, getMessageText(null, time, rake_money + "", 3));//自己失效
                } else {
                    pushJiGuangMessage(user_id, getMessageText(Origin_User.getNick_name(), time, rake_money + "", 3));//粉丝失效
                }
            }
        }
    }

    /**
     * 向佣金变化消息表，插入一条消息
     * messagetype 1 直接购收益 2 粉丝返， 3人头奖励  4，普通扣除
     */
    private void insertNormalMessage(User user, User Origin_User, Order order, OrderFansRake fans) {
        int order_type = order.getType(); // 订单类型 1淘宝,2京东，3拼多多，4唯品会 （10信用卡）',
        int messagetype = 0;
        double ranke_money = 0;
        if (fans != null) {
            messagetype = 2;
            ranke_money = Double.parseDouble(fans.getUser_rake_back());
        } else {
            messagetype = 1;
            ranke_money = Double.parseDouble(order.getUser_rake_back_yugu());
        }
//        if (order.getStatus() == 4) {
//            messagetype = 4;//无效，扣除
//        }
        /*******新增信用卡逻辑****/
        if (order.getType() == 10 && (order.getStatus() == 7 || order.getStatus() == 8)) {//信用卡订单
//            insertNormalMessage(user, user, order, null);//自购消息
            messagetype = 4;//无效，扣除
        } else if (order.getType() != 10 && order.getStatus() == 4) {
            messagetype = 4;//无效，扣除
        }
        insertMessage(user.getId(), Origin_User, order.getOrder_id(), order_type, ranke_money, Double.parseDouble(order.getActual_amount()), messagetype);
    }

    /**
     * 更新粉丝预估
     *
     * @param user
     * @param money
     */
    private void updateFans_estimate(User user, Order order, double money) {
        // Map map=new HashMap();
        UserMoney map = new UserMoney();
        map.setUser_id(user.getId());
//        //map.put("user_id",user.getId());
//        if (order.getStatus() == 2) {//订单状态 1-订单结算 2-订单付款 3-订单未付款 4-订单失效
//            map.setFans_estimate(money);
//            // map.put("fans_estimate",money);
//            //map.put("operate",1);////加金额
//        } else if (order.getStatus() == 4) {
//            map.setFans_estimate(0 - money);
//            // map.put("fans_estimate",0-money);
//            // map.put("operate",2);//减金额
//            Map map1 = new HashMap();
//            map1.put("order_id", order.getOrder_id());
//            map1.put("status", order.getStatus());
//            userMoneyMapper.updateFansRake(map1);
//        } else if (order.getStatus() == 1) {//结算更新可提现余额
//
//
//            map.setNormal_balance(money);
//            map.setAccumulated(money);
//            map.setFans_estimate(0 - money);
//            // map.put("fans_estimate",0-money);
//            //  map.put("normal_balance",money);
//            // map.put("accumulated",money);
//            //  map.put("operate",1);////加金额
//            Map map1 = new HashMap();
//            map1.put("order_id", order.getOrder_id());
//            map1.put("status", order.getStatus());
//            userMoneyMapper.updateFansRake(map1);
//        }

        /*******新增信用卡逻辑****/
        /***
         * 卡多分订单状态： 000 老户订单 001 带查询 002审核中 003审核通过 004 审核拒绝 005 未完成 006 异常订单
         *
         * jz_order 订单状态： 1-订单结算 2-订单付款 3-订单未付款 4-订单失效
         *            当type = 10   ,1订单结算 2 审核通过，3 审核中 ， 4 审核不 通过 5带查询  6未完成7 异常订单 8 失效订单
         * */
        if(order.getType() == 10){
            if (order.getStatus() == 2) {//订单状态 1-订单结算 2-订单付款 3-订单未付款 4-订单失效
                map.setFans_estimate(money);
            } else if (order.getStatus() == 7 || order.getStatus() == 8) {
                map.setFans_estimate(0 - money);
                Map map1 = new HashMap();
                map1.put("order_id", order.getOrder_id());
                map1.put("status", order.getStatus());
                userMoneyMapper.updateFansRake(map1);
            } else if (order.getStatus() == 1) {//结算更新可提现余额
                map.setNormal_balance(money);
                map.setAccumulated(money);
                map.setFans_estimate(0 - money);
                Map map1 = new HashMap();
                map1.put("order_id", order.getOrder_id());
                map1.put("status", order.getStatus());
                userMoneyMapper.updateFansRake(map1);
            }
        }else{
            if (order.getStatus() == 2) {//订单状态 1-订单结算 2-订单付款 3-订单未付款 4-订单失效
                map.setFans_estimate(money);
            } else if (order.getStatus() == 4) {
                map.setFans_estimate(0 - money);
                Map map1 = new HashMap();
                map1.put("order_id", order.getOrder_id());
                map1.put("status", order.getStatus());
                userMoneyMapper.updateFansRake(map1);
            } else if (order.getStatus() == 1) {//结算更新可提现余额
                map.setNormal_balance(money);
                map.setAccumulated(money);
                map.setFans_estimate(0 - money);
                Map map1 = new HashMap();
                map1.put("order_id", order.getOrder_id());
                map1.put("status", order.getStatus());
                userMoneyMapper.updateFansRake(map1);
            }
        }

        userMoneyMapper.updateUserMoney(map);
    }

    /**
     * 操作用户提现状态，
     *
     * @param userid
     * @param status 0 审核拒绝 1成功或通过
     * @param type   钱的类型 1 普通  2奖励  3活动佣金
     */
    public void txUpdate(int userid, int status, double money, int type) {
        UserMoney map = new UserMoney();
        map.setUser_id(userid);
        if (status == 0) {//审核拒绝 提现
            Map balance = new HashMap();
            balance.put("user_id", userid);
            balance.put("money", money);
            balance.put("type", Constant.BALANCE_TYPE_TX_FAILD);//取消或拒绝提现
            balance.put("action_type", Constant.BALANCE_ACTION_ADD);//拒绝提现，把钱返回给用户账号
            balance.put("remark", "拒绝提现-返还");
            userMoneyMapper.insertBalanceDetailNew(balance);

            if (type == 1) {//普通
                map.setNormal_balance(money);
            } else if (type == 2) {//奖励金余额
                map.setBounty_balance(money);
            }else if (type == 3) {//活动佣金余额
                map.setActivity_balance(money);
            }
            userMoneyMapper.updateUserMoney(map);
        } else if (status == 1) {//提现
            Map balance = new HashMap();
            balance.put("user_id", userid);
            balance.put("money", money);
            balance.put("type", Constant.BALANCE_TYPE_TX_SUCCESS);//提现
            balance.put("action_type", Constant.BALANCE_ACTION_REDUCE);
            balance.put("remark", "提现");
            userMoneyMapper.insertBalanceDetailNew(balance);

            if (type == 1) {//普通
                map.setNormal_balance(0 - money);
            } else if (type == 2) {//奖励金余额
                map.setBounty_balance(0 - money);
            } else if (type == 3) {//活动佣金余额
                map.setActivity_balance(0 - money);
            }
            userMoneyMapper.updateUserMoney(map);
        }
    }


    /**
     * 更新 普通下单预估
     *
     * @param user
     * @param order
     * @param money
     */
    private void updateOwner_estimate(User user, Order order, double money, int redmoney) {
        // Map map=new HashMap();
        UserMoney map = new UserMoney();
        map.setUser_id(user.getId());
//        if (order.getStatus() == 2) {//订单状态 1-订单结算 2-订单付款 3-订单未付款 4-订单失效
//            map.setOwner_estimate(money + redmoney);
//        } else if (order.getStatus() == 4) {
//            map.setOwner_estimate(0 - money - redmoney);
//        } else if (order.getStatus() == 1) {//结算
//            Map balance = new HashMap();
//            balance.put("user_id", user.getId());
//            balance.put("origin_id", user.getId());
//            balance.put("money", money + redmoney);
//            balance.put("action_type", Constant.BALANCE_ACTION_ADD);
//            balance.put("type", order.getBuytype() == 0 ? Constant.BALANCE_TYPE_BUY_SELF : Constant.BALANCE_TYPE_SHARE);
//            balance.put("remark", order.getBuytype() == 0 ? "自购" : "分享");
//            balance.put("order_id", order.getOrder_id());
//            userMoneyMapper.insertBalanceDetailNew(balance);
//            if (redmoney > 0) {
//                addRedPacket(user.getId(), order.getOrder_id(), redmoney);
//            }
//
//            map.setOwner_estimate(0 - money - redmoney);
//            map.setNormal_balance(money + redmoney);
//            map.setAccumulated(money + redmoney);
//        }
        /*******新增信用卡逻辑****/
        /***
         *  当type = 10   ,1订单结算 2 审核通过，3 审核中 ， 4 审核不 通过 5带查询  6未完成7 异常订单 8 失效订单
         * */
        if (order.getType() == 10) { //卡多分信用卡
            if (order.getStatus() == 2) {
                map.setOwner_estimate(money + redmoney);
            } else if (order.getStatus() == 7 || order.getStatus() == 8) {
                map.setOwner_estimate(0 - money - redmoney);
            } else if (order.getStatus() == 1) {//结算
                Map balance = new HashMap();
                balance.put("user_id", user.getId());
                balance.put("origin_id", user.getId());
                balance.put("money", money + redmoney);
                balance.put("action_type", Constant.BALANCE_ACTION_ADD);
                balance.put("type", order.getBuytype() == 0 ? Constant.BALANCE_TYPE_BUY_SELF : Constant.BALANCE_TYPE_SHARE);
                balance.put("remark", order.getBuytype() == 0 ? "自购" : "分享");
                balance.put("order_id", order.getOrder_id());
                userMoneyMapper.insertBalanceDetailNew(balance);
                if (redmoney > 0) {
                    addRedPacket(user.getId(), order.getOrder_id(), redmoney);
                }

                map.setOwner_estimate(0 - money - redmoney);
                map.setNormal_balance(money + redmoney);
                map.setAccumulated(money + redmoney);
            }
        } else {
            if (order.getStatus() == 2) {//订单状态 1-订单结算 2-订单付款 3-订单未付款 4-订单失效
                map.setOwner_estimate(money + redmoney);
            } else if (order.getStatus() == 4) {
                map.setOwner_estimate(0 - money - redmoney);
            } else if (order.getStatus() == 1) {//结算
                Map balance = new HashMap();
                balance.put("user_id", user.getId());
                balance.put("origin_id", user.getId());
                balance.put("money", money + redmoney);
                balance.put("action_type", Constant.BALANCE_ACTION_ADD);
                balance.put("type", order.getBuytype() == 0 ? Constant.BALANCE_TYPE_BUY_SELF : Constant.BALANCE_TYPE_SHARE);
                balance.put("remark", order.getBuytype() == 0 ? "自购" : "分享");
                balance.put("order_id", order.getOrder_id());
                userMoneyMapper.insertBalanceDetailNew(balance);
                if (redmoney > 0) {
                    addRedPacket(user.getId(), order.getOrder_id(), redmoney);
                }

                map.setOwner_estimate(0 - money - redmoney);
                map.setNormal_balance(money + redmoney);
                map.setAccumulated(money + redmoney);
            }
        }
        userMoneyMapper.updateUserMoney(map);
    }

    /**
     * 给用户增加红包收入记录
     *
     * @param userid
     * @param orderid
     * @param money
     */
    private void addRedPacket(int userid, String orderid, double money) {
        Map balance = new HashMap();
        balance.put("user_id", userid);
        balance.put("money", money);
        balance.put("action_type", Constant.BALANCE_ACTION_ADD);
        balance.put("type", Constant.BALANCE_TYPE_ORDER_REDPAPER);
        balance.put("remark", "订单红包");
        balance.put("order_id", orderid);
        userMoneyMapper.insertBalanceDetailNew(balance);
      /*  UserMoney map = new UserMoney();
        map.setUser_id(userid);
        map.put("money", money);
        userMoneyMapper.updateUserMoney(map);*/
    }


    /**
     * 更新人头奖励佣金 历史累计总和，可提现奖励佣金
     */
    private void updateBounty_accumulated(User user, double money) {
        UserMoney map = new UserMoney();
        map.setUser_id(user.getId());
        map.setBounty_accumulated(money);
        map.setBounty_balance(money);
        // map.put("user_id",user.getId());
        //  map.put("bounty_balance",money);//，提现需要判断此值
        // map.put("bounty_accumulated",money);//累计收益
        userMoneyMapper.updateUserMoney(map);
    }

    /**
     * 从内存列表去查询,检查当前用户的向上一级是否是平级
     *
     * @param user
     * @return
     */
    private boolean checkUpVipLeveByList(List<User> userList, User user) {
        int startIndex = userList.indexOf(user) + 1;
        for (int i = startIndex; i < userList.size(); i++) {
            User upuser = userList.get(i);
            if (user.getLevel() == upuser.getLevel()) {
                return true;
            }
            if (upuser.getLevel() > user.getLevel()) {//如果遇到大于级别的，中断检查
                return false;
            }
        }
        return false;
    }

    /**
     * 检测是否向上还有更高级或平级出现
     *
     * @param userList
     * @param user
     * @return
     */
    private boolean checkUpVipLeveByList2(List<User> userList, User user) {
        int startIndex = userList.indexOf(user) + 1;
        for (int i = startIndex; i < userList.size(); i++) {
            User upuser = userList.get(i);

            if (upuser.getLevel() >= user.getLevel()) {//如果遇到大于级别的，中断检查
                return true;
            }
        }
        return false;
    }

    /**
     * 检查当前用户的向上一级是否是平级
     *
     * @param user
     * @return
     */
    private boolean checkUpVipLeve(User user) {
        Map map = new HashMap();
        // map.put("id",user.getIntroducer());
        //  User upuser=userMoneyMapper.getByUserId(map);
        // if(upuser!=null){
        Integer searchId = user.getIntroducer();
        while (true) {//继续找最近的VIP
            map.put("id", searchId);
            User upuser = userMoneyMapper.getByUserId(map);
            if (upuser != null) {//找到上一级,计算团队收益
                if (user.getLevel() == upuser.getLevel()) {
                    return true;
                }
                if (upuser.getLevel() > user.getLevel()) {//如果遇到大于级别的，中断检查
                    return false;
                }
                searchId = upuser.getIntroducer();
            } else {
                break;
            }
        }
        // }

        return false;
    }

    /**
     * 添加一条粉丝返佣记录，直返或间返，并一起关联查找团队CPS
     *
     * @param upuser
     * @param order
     * @param Origin_User
     * @param rate
     * @param type
     */
    private void insertFanceRake(List<User> userList, User upuser, Order order, User Origin_User, Double rate, String type) {
        if (Double.parseDouble(round(rate * Double.parseDouble(order.getRake_back()) + "")) <= 0) {//如果佣金为0,就不通知，不做处理
            return;
        }
        OrderFansRake fansRake = new OrderFansRake();
        fansRake.setOrder_id(order.getOrder_id());
        fansRake.setUser_id(upuser.getId());//用户ID
        fansRake.setOrigin_id(Origin_User.getId());//来源用户ID
        fansRake.setRake_rate(rate + "");
        fansRake.setRake_back(order.getRake_back());//总佣金
        fansRake.setUser_rake_back(round(rate * Double.parseDouble(order.getRake_back()) + ""));//该上级返佣
        fansRake.setRake_type(type);
        fansRake.setStatus(order.getStatus());
        userMoneyMapper.insertFansRake(fansRake);
        insertNormalMessage(upuser, Origin_User, order, fansRake);
        updateFans_estimate(upuser, order, Double.parseDouble(fansRake.getUser_rake_back()));
        if (checkUpVipLeveByList2(userList, upuser)) {
            repeatGroupCPS(userList, upuser, order, Origin_User, upuser.getLevel(), true);
        }

    }


    /**
     * CPS方式返佣
     *
     * @param upuser
     * @param order
     * @param Origin_User
     * @param rate
     * @param type
     */
    private void insertFanceRakeCPS(User upuser, Order order, User Origin_User, Double rate, String type) {
        if (Double.parseDouble(round(rate * Double.parseDouble(order.getRake_back()) + "")) <= 0) {//如果佣金为0,就不通知，不做处理
            return;
        }
        OrderFansRake fansRake = new OrderFansRake();
        fansRake.setOrder_id(order.getOrder_id());
        fansRake.setUser_id(upuser.getId());//用户ID
        fansRake.setOrigin_id(Origin_User.getId());//来源用户ID
        fansRake.setRake_rate(rate + "");
        fansRake.setRake_back(order.getRake_back());//总佣金
        fansRake.setUser_rake_back(round(rate * Double.parseDouble(order.getRake_back()) + ""));//该上级返佣
        fansRake.setRake_type(type);
        fansRake.setStatus(order.getStatus());
        userMoneyMapper.insertFansRake(fansRake);
        insertNormalMessage(upuser, Origin_User, order, fansRake);
        updateFans_estimate(upuser, order, Double.parseDouble(fansRake.getUser_rake_back()));
    }

    /**
     * 插入人头奖励分成,给上级返佣，CPS
     *
     * @param
     * @param
     * @param Origin_User
     * @param
     * @param type
     */
    private void insertGiftRakeCPS(User upuser, OrderGift gift, User Origin_User, String money, String type) {

        OrderGiftRake rake = new OrderGiftRake();
        rake.setOrder_id(gift.getOrder_id());
        rake.setOrigin_id(Origin_User.getId());
        rake.setUser_id(upuser.getId());
        rake.setRake_type(type);
        rake.setUser_rake_back(money + "");
        userMoneyMapper.insertGiftRake(rake);
        updateBounty_accumulated(upuser, Double.parseDouble(money));
        insertMessage(upuser.getId(), Origin_User, gift.getOrder_id(), 0, Double.parseDouble(rake.getUser_rake_back()), Double.parseDouble(gift.getActual_amount()), 3);

    }

    /**
     * 递归 遍历当前会员的上一级团队奖励
     *
     * @param currUser
     * @param order
     * @param Origin_User
     * @param uplevel
     */
    private void repeatGroupGift(List<User> userList, User currUser, OrderGift order, User Origin_User, int uplevel, boolean allowLevelEqual) {
        User upuser = getUpUserByUser(userList, currUser);
        if (upuser != null) {//找到上一级,计算团队收益
            if (upuser.getLevel() < uplevel) {
                repeatGroupGift(userList, upuser, order, Origin_User, uplevel, allowLevelEqual);//继续找更高LEVE VIP  上级
            } else if (uplevel == 1) {//会员
                if (upuser.getLevel() == currUser.getLevel()) {// 平级会员 直接 跳过
                    repeatGroupGift(userList, upuser, order, Origin_User, uplevel, allowLevelEqual);//继续找更高LEVE VIP  上级
                } else if (upuser.getLevel() == 2) {
                    //奖励50
                    uplevel = upuser.getLevel();
                    insertGiftRakeCPS(upuser, order, Origin_User, "50", "会员团队50");
                    if (checkUpVipLeveByList2(userList, upuser)) {//预判断是否有上级
                        repeatGroupGift(userList, upuser, order, Origin_User, uplevel, allowLevelEqual);//继续找更高LEVE VIP  上级
                    }

                } else if (upuser.getLevel() == 3) {
                    //奖励100
                    uplevel = upuser.getLevel();
                    insertGiftRakeCPS(upuser, order, Origin_User, "100", "会员团队100");
                    if (checkUpVipLeveByList2(userList, upuser)) {//预判断是否有上级
                        repeatGroupGift(userList, upuser, order, Origin_User, uplevel, allowLevelEqual);//继续找更高LEVE VIP  上级
                    }
                }

            } else if (uplevel == 2) {//运营商
                if (upuser.getLevel() == 2) {//运营商平级

                    if (allowLevelEqual) {
                        //奖励20
                        uplevel = upuser.getLevel();
                        insertGiftRakeCPS(upuser, order, Origin_User, "20", "直属运营商20");
                    }
                    if (checkUpVipLeveByList2(userList, upuser)) {//预判断是否有上级
                        repeatGroupGift(userList, upuser, order, Origin_User, uplevel, false);//继续找更高LEVE VIP  上级
                    }

                } else if (upuser.getLevel() == 3) {
                    //奖励50
                    uplevel = upuser.getLevel();
                    insertGiftRakeCPS(upuser, order, Origin_User, "50", "运营商团队50");
                    if (checkUpVipLeveByList2(userList, upuser)) {//预判断上级是否是平级
                        repeatGroupGift(userList, upuser, order, Origin_User, uplevel, allowLevelEqual);//继续找更高LEVE VIP  上级
                    }

                } else {
                    repeatGroupGift(userList, upuser, order, Origin_User, uplevel, allowLevelEqual);//继续找更高LEVE VIP  上级
                }
            } else if (uplevel == 3) {// 联创
                if (upuser.getLevel() == 3) {
                    //奖励10
                    uplevel = upuser.getLevel();
                    insertGiftRakeCPS(upuser, order, Origin_User, "10", "联创团队10");
                } else {
                    repeatGroupGift(userList, upuser, order, Origin_User, uplevel, allowLevelEqual);//继续找更高LEVE VIP  上级
                }
                //
            }
        } else if (currUser.getLevel() >= uplevel) {
            if (currUser.getLevel() == 2) {
                if (uplevel == 1) {
                    insertGiftRakeCPS(currUser, order, Origin_User, "50", "会员团队50");
                } else if (uplevel == 2) {
                    insertGiftRakeCPS(currUser, order, Origin_User, "20", "直属运营商20");
                }
            } else if (currUser.getLevel() == 3) {
                if (uplevel == 1) {
                    insertGiftRakeCPS(currUser, order, Origin_User, "100", "会员团队100");
                } else if (uplevel == 2) {
                    insertGiftRakeCPS(currUser, order, Origin_User, "50", "运营商团队50");
                } else if (uplevel == 3) {
                    insertGiftRakeCPS(currUser, order, Origin_User, "10", "联创团队10");
                }
            }

        }
    }

    /**
     * 遍历当前会员的上一级团队收益,递归
     *
     * @param
     */
    private void repeatGroupCPS(List<User> userList, User currUser, Order order, User Origin_User, int uplevel, boolean allowLevelEqual) {
        // User currUser=user;
        // boolean allowLevelEqual=true;//是否允许平级，已经将自身减少过比例 ，允许平级收益百分比
        //Map map=new HashMap();
        // map.put("id",currUser.getIntroducer());
        User upuser = getUpUserByUser(userList, currUser);
        if (upuser != null) {//找到上一级,计算团队收益
            if (upuser.getLevel() < uplevel) {
                repeatGroupCPS(userList, upuser, order, Origin_User, uplevel, allowLevelEqual);//继续找更高LEVE VIP  上级
            } else if (uplevel == 1) {//会员
                if (upuser.getLevel() == 1) {
                    if (allowLevelEqual) {
                        //给upser返5%  //直属超级团队
                        uplevel = upuser.getLevel();
                        insertFanceRakeCPS(upuser, order, Origin_User, 0.05, "超级会员团队CPS5");
                    }
                    repeatGroupCPS(userList, upuser, order, Origin_User, uplevel, false);//继续找更高LEVE VIP  上级
                } else if (upuser.getLevel() == 2) {//直属
                    if (checkUpVipLeveByList(userList, upuser)) {//预判断上级是否是平级
                        //给upser 返4
                        insertFanceRakeCPS(upuser, order, Origin_User, 0.03, "超级会员团队CPS3");
                        uplevel = upuser.getLevel();
                        repeatGroupCPS(userList, upuser, order, Origin_User, uplevel, true);//继续找更高LEVE VIP  上级
                    } else {
                        //给upser 返6
                        uplevel = upuser.getLevel();
                        insertFanceRakeCPS(upuser, order, Origin_User, 0.05, "超级会员团队CPS5");
                        if (checkUpVipLeveByList2(userList, upuser)) {//预判断是否有上级
                            repeatGroupCPS(userList, upuser, order, Origin_User, uplevel, false);//继续找更高LEVE VIP  上级

                        }
                    }
                } else if (upuser.getLevel() == 3) {
                    if (checkUpVipLeveByList(userList, upuser)) {//预判断上级是否是平级
                        //给upser 返9
                        uplevel = upuser.getLevel();
                        insertFanceRakeCPS(upuser, order, Origin_User, 0.07, "超级会员团队CPS7");
                        repeatGroupCPS(userList, upuser, order, Origin_User, uplevel, true);//继续找更高LEVE VIP  上级
                    } else {
                        //给upser 返10
                        uplevel = upuser.getLevel();
                        insertFanceRakeCPS(upuser, order, Origin_User, 0.08, "超级会员团队CPS8");
                        if (checkUpVipLeveByList2(userList, upuser)) {//预判断是否有上级
                            repeatGroupCPS(userList, upuser, order, Origin_User, uplevel, false);//继续找更高LEVE VIP  上级

                        }
                    }
                }
            } else if (uplevel == 2) {//运营商
                if (upuser.getLevel() == 2) {
                    if (allowLevelEqual) {
                        //给upser返2%
                        uplevel = upuser.getLevel();
                        insertFanceRakeCPS(upuser, order, Origin_User, 0.02, "运营商团队CPS2");
                    }
                    if (checkUpVipLeveByList2(userList, upuser)) {//预判断是否有上级
                        repeatGroupCPS(userList, upuser, order, Origin_User, uplevel, false);//继续找更高LEVE VIP  上级

                    }
                } else {
                    if (upuser.getLevel() == 3) {
                        if (checkUpVipLeveByList(userList, upuser)) {//预判断上级是否是平级
                            //给upser 返3
                            uplevel = upuser.getLevel();
                            insertFanceRakeCPS(upuser, order, Origin_User, 0.02, "运营商团队CPS2");
                            repeatGroupCPS(userList, upuser, order, Origin_User, uplevel, true);//继续找更高LEVE VIP  上级
                        } else {
                            //给upser 返4
                            uplevel = upuser.getLevel();
                            insertFanceRakeCPS(upuser, order, Origin_User, 0.03, "运营商团队CPS3");
                            //repeatGroupCPS(upuser,order,Origin_id,uplevel,false);//继续找更高LEVE VIP  上级
                        }
                    }

                }
            } else if (uplevel == 3) {//联创
                if (upuser.getLevel() == 3) {//联创平级的情况
                   /* if (allowLevelEqual) {
                        //给upser返1% 然后结束整个返佣流程,不再递归
                        insertFanceRakeCPS(upuser, order, Origin_User, 0.01, "联创团队CPS1");
                    } else {//当前联创需要计算一次*/
                       /* if (uplevel == 1) {
                            insertFanceRakeCPS(currUser, order, Origin_User, 0.9, "超级会员团队CPS9");
                        } else if (uplevel == 2) {
                            insertFanceRakeCPS(currUser, order, Origin_User, 0.03, "运营商团队CPS3");
                        }*/

                    //}
                    insertFanceRakeCPS(upuser, order, Origin_User, 0.01, "联创团队CPS1");
                } else {
                    if (checkUpVipLeveByList2(userList, upuser)) {//预判断是否有上级
                        repeatGroupCPS(userList, upuser, order, Origin_User, uplevel, false);//继续找更高LEVE VIP  上级

                    }
                }
            }
        } else {
            if (currUser.getLevel() >= uplevel) {
                if (currUser.getLevel() == 1) {
                    if (uplevel == 1) {
                        insertFanceRakeCPS(currUser, order, Origin_User, 0.05, "超级会员团队CPS5");
                    }
                } else if (currUser.getLevel() == 2) {
                    if (uplevel == 1) {
                        insertFanceRakeCPS(currUser, order, Origin_User, 0.05, "超级会员团队CPS5");
                    } else if (uplevel == 2) {
                        insertFanceRakeCPS(currUser, order, Origin_User, 0.02, "运营商团队CPS2");
                    }
                } else if (currUser.getLevel() == 3) {
                    if (uplevel == 1) {
                        insertFanceRakeCPS(currUser, order, Origin_User, 0.08, "超级会员团队CPS8");
                    } else if (uplevel == 2) {
                        insertFanceRakeCPS(currUser, order, Origin_User, 0.03, "运营商团队CPS3");
                    } else if (uplevel == 3) {
                        insertFanceRakeCPS(currUser, order, Origin_User, 0.01, "联创团队CPS1");
                    }
                }

            }
        }


    }


    /**
     * 保留固定位数小数<br>
     * 采用四舍五入策略 {@link RoundingMode#HALF_UP}<br>
     * 例如保留2位小数：123.456789 =》 123.46
     *
     * @param numberStr 数字值的字符串表现形式
     * @param
     * @return 新值 2位小数
     */
    public static String round(String numberStr) {
        BigDecimal value = new BigDecimal(numberStr);
        return value.setScale(2, RoundingMode.HALF_UP).toString();
    }

    /***
     * 信用卡订单 ：激光推送
     * @param userId 用户id
     * @param rakeMoney  佣金
     * @param orderId   信用卡订单号 （客户号）
     * @param bankName 卡行名称
     * */
    public void addCreditCardMessageRakeMoney(Integer userId, Double rakeMoney, String orderId, String bankName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date()).toString();
        pushJiGuangMessage(userId, getMessageText(bankName + "信用卡 客户号为:" + orderId, time, rakeMoney + "", 10));//信用卡订单返佣
    }

}
